<template>
  <!-- 线索分配规则定义 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      :list="topFilterInit"
      :cols="3"
      labelWidth="120"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isPagination="false"
      columnsRef="potenCus_basedata_clueDistributeConfig_index_01"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-tickets" @click="save()">保存</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="dialogHandle('','add')"
        >新增</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportHandle()"
        >导出</el-button>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="importHandle()">导入</el-button>
      </template>
    </FilterTable>

    <Drawer
      title="线索分配规则维护"
      :visible.sync="visibleDrawer"
      :width="920"
      :closable="false"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <addDialog v-model="initData" @close="dialogClose" />
    </Drawer>

    <BaseDialog
      :visible.sync="UploadFileIsShow"
      title="导入"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <importFile title="导入" :actionUrl="actionUrl" @close="successHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import addDialog from './addDialog';
import { dictionary } from '@/utils/dictMixin';
import personnelMadal from '@/pages/cms-common/user';
import { getClueDistributeConfig, getListByDept, saveConfig, exportConfig, importPackages } from '@/api/potenCus/basedata/clueDistributeConfig/index';
import { region } from '@/api/cms-common/region';
import { getRegion, getCommunity, getProvinceByLoginDeptId } from '@/api/cms-common/dealerdata/index';
import { dealerCommon } from '@/api/cms-api/origin/commonDealerType'; //渠道类型工具类
import { formatdateByDay } from '@/utils';
import * as types from '@/api/cms-api/origin/construct/dealer/types';
import { getUserInfo } from '@/api/login/index';
import { exportExcelFile } from '@/utils/index';
export default {
  mixins: [dictionary, region, dealerCommon],
  components: {
    addDialog,
    personnelMadal
  },
  data() {
    return {
      dataSource: [],
      isSelectColumn: false,
      visibleDrawer: false,
      visibleDrawerShow: false,
      initData: {},
      topFilterInit: this.topFilterInitFun(),
      fetchParams: {}, //参数
      columns: this.creatHeader(),
      visiblePersonnel: false, //人员弹窗开关
      userId: '',
      userName: '',
      fetchApi: getListByDept,
      userInfo: {},
      exportLoading: false,
      UploadFileIsShow: false,
      form: {
        fileList: []
      },
      actionUrl: '/api/cluecenter/clueDistributeConfig/importPackages'
    };
  },
  mounted() {
    //初始化省份信息
    this.initProvince();
    //初始化列表信息
    this.init();

    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    async init() {
      //用户信息
      let res = await getUserInfo();
      if (res.resultCode === 200) {
        this.userInfo = res.data.userInfo;
      } else {
        this.$notify.error({ title: '提示信息', message: '获取用户信息失败!' });
      }
    },

    //搜索数据
    topFilterInitFun() {
      return [
        // { type: 'INPUT', label: '经销商代码', fieldName: 'ownerCode', placeholder: '请输入' },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCodes',
          placeholder: '请输入',
          itemList: []
        },
        { type: 'INPUT', label: '经销商名称', fieldName: 'dealerName', placeholder: '请输入' },

        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          placeholder: '请选择',
          itemList: [],
          change: value => {
            this.initCity(value);
          }
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          placeholder: '请选择',
          itemList: [],
          change: value => {
            this.initTown(value);
          }
        },
        { type: 'MULTIPLE_SELECT', label: '县区', fieldName: 'countyIds', placeholder: '请选择', itemList: [] }
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      if (Array.isArray(val.countyIds)) {
        val.countyId = val.countyIds.join(',');
      }
      this.fetchParams = Object.assign({}, val);
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '省份',
          dataIndex: 'provinceId',
          sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.provinceId)}</span>;
          }
        },
        {
          title: '城市',
          dataIndex: 'cityId',
          sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.cityId)}</span>;
          }
        },
        {
          title: '县区',
          dataIndex: 'countyId',
          sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.countyId)}</span>;
          }
        },
        { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
        { title: '经销商名称', dataIndex: 'dealerName', sorter: true },
        {
          title: '是否黑名单',
          dataIndex: 'isBlacklist',
          sorter: false,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.isBlacklist, '1004')}</span>;
          }
        },
        { title: '有区县线索分配数量', dataIndex: 'areaNum', sorter: false, editType: 'text', editable: true, defaultEditable: true, editRequired: true },
        { title: '无区县线索分配数量', dataIndex: 'noAreaNum', sorter: false, editType: 'text', editable: true, defaultEditable: true, editRequired: true }
      ];
    },
    // 人员打开窗口 -传数据
    personnelHandle() {
      this.visiblePersonnel = true;
    },
    // 清空人员数据
    clearPersonnelHandle() {
      //清空数据内容
      this.userId = '';
      this.userName = '';

      //清空人员名称
      this.topFilterInit.find(item => item.fieldName === 'userName').initialValue = '';
    },
    // 人员关闭窗口 -返回数据
    closePersonnel(data) {
      if (data.type != 'close' && data.data && data.data.length > 0) {
        //清空数据内容
        this.userId = '';
        this.userName = '';

        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接用户ID
          if (this.userId == '') {
            this.userId = x.userId;
          } else {
            this.userId += ',' + x.userId;
          }

          //使用逗号分隔拼接用户姓名
          if (this.userName == '') {
            this.userName = x.employeeName;
          } else {
            this.userName += ',' + x.employeeName;
          }
        });
        //显示人员名称
        this.topFilterInit.find(item => item.fieldName === 'userName').initialValue = this.userName;
      }
      //关闭弹窗
      this.visiblePersonnel = data.visible;
    },
    //初始化所在省份
    async initProvince() {
      // let pl = this.createRegionList();
      // this.topFilterInit.find(item => item.fieldName === 'provinceId').itemList = pl;
      let res = await getProvinceByLoginDeptId();
      if (res.resultCode === 200) {
        this.topFilterInit.find(item => item.fieldName === 'provinceId').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
      }
    },
    //初始化所在市数据
    async initCity(provinceId) {
      //清空市
      this.topFilterInit.find(item => item.fieldName === 'cityId').initialValue = '';
      //清空县
      this.topFilterInit.find(item => item.fieldName === 'countyIds').initialValue = '';
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      this.topFilterInit.find(item => item.fieldName === 'cityId').itemList = cl;
    },
    //初始化所在县数据
    async initTown(cityId) {
      //清空县
      this.topFilterInit.find(item => item.fieldName === 'countyIds').initialValue = '';
      if (!cityId || cityId == null || typeof cityId == 'undefined') {
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      this.topFilterInit.find(item => item.fieldName === 'countyIds').itemList = tl;
    },
    //新增、修改
    dialogHandle(row, type) {
      this.visibleDrawer = true;
      const pram = {
        type: type,
        rowData: row,
        userInfo: this.userInfo
      };
      this.initData = pram;
    },
    //关闭新增、修改
    dialogClose(data) {
      this.visibleDrawer = false;
      if (data.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    //明细
    dialogHandleShow(row, type) {
      this.visibleDrawerShow = true;
      const pram = {
        type: type,
        rowData: row
      };
      this.initData = pram;
    },
    //关闭明细
    dialogCloseShow(data) {
      this.visibleDrawerShow = false;
      if (data.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //点击保存
    async save() {
      if (this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR() == null) {
        let clueDistributeConfigList = this.$refs.table.$refs.pageTable.list;
        let res = await saveConfig(clueDistributeConfigList);
        if (res) {
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '操作成功!' });
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '操作失败!' });
            // this.closeDialog();
          }
        }
      } else {
        this.$notify.error({ title: '提示信息', message: '填写有错误，请核查!' });
      }
    },
    // 导出 （根据当前登录用户所在事业部查询数据）
    async exportHandle() {
      let params = JSON.parse(JSON.stringify(this.fetchParams));

      this.exportLoading = true;
      await exportConfig({ ...params })
        .then(response => {
          exportExcelFile(response.data, '线索分配规则定义');
          this.exportLoading = false;
        })
        .catch(err => {
          this.exportLoading = false;
          console.log(err);
        });
    },
    // 导入
    importHandle() {
      this.handleType = 'import';
      this.UploadFileIsShow = true;
      this.form.fileList = [];
    },

    successHandler(val) {
      if (val && val.length > 0) {
        console.log(val, '导入');

        this.form.fileList = val;
      }
      this.UploadFileIsShow = false;
      this.fetchParams = { ...this.fetchParams };
    }
  }
};
</script>

<style lang="less" scoped>
</style>
